package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private UserService userService;

    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }

    @CacheEvict(value ="user", key ="#id")
    // 当deleteUser方法被调用时，缓存名称为"users"的缓存中键为id的数据将被移除。
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }

    @CachePut(value = "users",key = "#user.id")
    public User updateUser(User user){
        return user;
    }
    //value属性设置为"users"，这是缓存名称。key属性设置为"#user.id"
    // 这表示使用方法参数user的id属性作为缓存键
    // 每次调用updateUser方法时，都会执行方法体，并将返回值放入名为users的缓存中，键为用户的ID
    // 这里的user.id是在方法执行完之后获取的最新数据
    // 所以，虽然在传入的参数中，user.id是空值，但在返回时，已经通过配置的雪花算法生成了该id。
    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }


    @Cacheable(cacheNames = "users", key = "#id",unless = "#result =null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

    @GetMapping("/list")
    public List<User> list(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null,User::getId,user.getId());
        queryWrapper.eq(user.getName() != null,User::getName,user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }
}
